/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.iasd.youthshelter.wizards.core.events.graduation;

import java.awt.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.openide.util.Lookup;
import pt.iasd.youthshelter.datamodel.Pathfinder;
import pt.iasd.youthshelter.datamodel.service.PathfinderController;
import pt.iasd.youthshelter.wizards.core.ListSorter;
import pt.iasd.youthshelter.wizards.core.WizardKeys;

public final class GraduationSchoolVisualPanel2 extends JPanel implements DocumentListener {
    private static final ResourceBundle bundle = java.util.ResourceBundle.getBundle("pt/iasd/youthshelter/wizards/core/Bundle");
    /* Logging object. */
    private Logger logger = Logger.getLogger(this.getClass().getName());
    
    /* Pathfinder lists that support visual jList objects. */
    private List<Pathfinder> assigned;
    private List<Pathfinder> available;

    /**
     * Creates new form GraduationSchoolVisualPanel2
     */
    public GraduationSchoolVisualPanel2() {
        this(null);
    }
    
    /**
     * Creates new form GraduationSchoolVisualPanel2
     */
    public GraduationSchoolVisualPanel2(List<Pathfinder> assigned) {
        this.assigned = ListSorter.sortPathfindersByName(assigned);
        if(this.assigned == null) {
            this.assigned = new ArrayList<>();
        }
        initComponents();
    }

    @Override
    public String getName() {
        return WizardKeys.PROP_GSCHOOL_STEPS[1];
    }

    public List<Pathfinder> getAssigned() {
        return assigned;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        PathfinderScrollPane = new javax.swing.JScrollPane();
        PathfinderList = new javax.swing.JList();
        WithdrawButton = new javax.swing.JButton();
        IncludeButton = new javax.swing.JButton();
        GraduationScrollPane = new javax.swing.JScrollPane();
        GraduationList = new javax.swing.JList();

        PathfinderScrollPane.setMaximumSize(new java.awt.Dimension(230, 250));
        PathfinderScrollPane.setMinimumSize(new java.awt.Dimension(230, 250));
        PathfinderScrollPane.setPreferredSize(new java.awt.Dimension(230, 250));

        PathfinderList.setModel(buildPathfinderListDataModel());
        PathfinderList.setCellRenderer(new PathfinderRenderer());
        PathfinderList.setMaximumSize(new java.awt.Dimension(30000, 30000));
        PathfinderList.setMinimumSize(new java.awt.Dimension(32, 32));
        PathfinderList.setPreferredSize(new java.awt.Dimension(200, 200));
        PathfinderList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                PathfinderListValueChanged(evt);
            }
        });
        PathfinderScrollPane.setViewportView(PathfinderList);

        org.openide.awt.Mnemonics.setLocalizedText(WithdrawButton, bundle.getString("Buttons.Withdraw"));
        WithdrawButton.setEnabled(false);
        WithdrawButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                WithdrawButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(IncludeButton, bundle.getString("Buttons.Include"));
        IncludeButton.setEnabled(false);
        IncludeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                IncludeButtonActionPerformed(evt);
            }
        });

        GraduationScrollPane.setMaximumSize(new java.awt.Dimension(230, 250));
        GraduationScrollPane.setMinimumSize(new java.awt.Dimension(230, 250));
        GraduationScrollPane.setPreferredSize(new java.awt.Dimension(230, 250));

        GraduationList.setModel(buildAssignedPathfindersListModel());
        GraduationList.setCellRenderer(new PathfinderRenderer());
        GraduationList.setMaximumSize(new java.awt.Dimension(30000, 30000));
        GraduationList.setMinimumSize(new java.awt.Dimension(32, 32));
        GraduationList.setPreferredSize(new java.awt.Dimension(200, 200));
        GraduationList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                GraduationListValueChanged(evt);
            }
        });
        GraduationScrollPane.setViewportView(GraduationList);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(PathfinderScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(WithdrawButton)
                    .addComponent(IncludeButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(GraduationScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(PathfinderScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(GraduationScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(95, 95, 95)
                        .addComponent(IncludeButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(WithdrawButton)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void PathfinderListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_PathfinderListValueChanged
        if(PathfinderList.isSelectionEmpty()) {
            IncludeButton.setEnabled(false);
        } else {
            GraduationList.clearSelection();
            IncludeButton.setEnabled(true);
            WithdrawButton.setEnabled(false);
        }
    }//GEN-LAST:event_PathfinderListValueChanged

    private void GraduationListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_GraduationListValueChanged
        if(GraduationList.isSelectionEmpty()) {
            WithdrawButton.setEnabled(false);
        } else {
            PathfinderList.clearSelection();
            WithdrawButton.setEnabled(true);
            IncludeButton.setEnabled(false);
        }
    }//GEN-LAST:event_GraduationListValueChanged

    private void WithdrawButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_WithdrawButtonActionPerformed
        List<Pathfinder> withdrawing = GraduationList.getSelectedValuesList();
        if(!withdrawing.isEmpty()) {
            available.addAll(withdrawing);
            available = ListSorter.sortPathfindersByName(available);
            assigned.removeAll(withdrawing);
        }
        reloadLists();
        firePropertyChange(WizardKeys.PROP_ANY, 0, 1);
    }//GEN-LAST:event_WithdrawButtonActionPerformed

    private void IncludeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_IncludeButtonActionPerformed
        List<Pathfinder> assigning = PathfinderList.getSelectedValuesList();
        if(!assigning.isEmpty()) {
            assigned.addAll(assigning);
            assigned = ListSorter.sortPathfindersByName(assigned);
            available.removeAll(assigning);
        }
        reloadLists();
        firePropertyChange(WizardKeys.PROP_ANY, 0, 1);
    }//GEN-LAST:event_IncludeButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList GraduationList;
    private javax.swing.JScrollPane GraduationScrollPane;
    private javax.swing.JButton IncludeButton;
    private javax.swing.JList PathfinderList;
    private javax.swing.JScrollPane PathfinderScrollPane;
    private javax.swing.JButton WithdrawButton;
    // End of variables declaration//GEN-END:variables

    @Override
    public void insertUpdate(DocumentEvent e) {
        changedUpdate(e);
    }

    @Override
    public void removeUpdate(DocumentEvent e) {
        changedUpdate(e);
    }

    @Override
    public void changedUpdate(DocumentEvent e) {
        firePropertyChange(WizardKeys.PROP_ANY, 0, 1);
    }
    
    // <editor-fold defaultstate="collapsed" desc="Inner Classes">
    private class PathfinderRenderer extends DefaultListCellRenderer {

        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if(value instanceof Pathfinder) {
                setText(((Pathfinder)value).getName());
            } else {
                setText("");
            }
            return this;
        }
    }// </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="List Data Loading Code">
    private DefaultListModel buildPathfinderListDataModel() {
        PathfinderController controller = Lookup.getDefault().lookup(PathfinderController.class);
        DefaultListModel model = new DefaultListModel();
        if(controller != null) {
            try{
                List<Pathfinder> loaded = ListSorter.sortPathfindersByName(controller.findActivePathfinderEntities());
                if(!loaded.isEmpty()) {
                    available = new ArrayList<Pathfinder>();
                    for(Pathfinder pathfinder : loaded) {
                        if(assigned == null || !assigned.contains(pathfinder)) {
                            available.add(pathfinder);
                            model.addElement(pathfinder);
                        }
                    }
                }
            } catch(Exception ex) {
                logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
            }
        }
        return model;
    }
    
    private DefaultListModel buildAssignedPathfindersListModel() {
        DefaultListModel model = new DefaultListModel();
        if(assigned != null) {
            for(Pathfinder pathfinder : assigned) {
                model.addElement(pathfinder);
            }
        }
        return model;
    }
    
    private void reloadLists() {
        PathfinderList.clearSelection();
        GraduationList.clearSelection();
        WithdrawButton.setEnabled(false);
        IncludeButton.setEnabled(false);
        DefaultListModel pathfinderModel = new DefaultListModel();
        for(Pathfinder pathfinder : available) {
            pathfinderModel.addElement(pathfinder);
        }
        PathfinderList.setModel(pathfinderModel);
        DefaultListModel graduationModel = new DefaultListModel();
        for(Pathfinder pathfinder : assigned) {
            graduationModel.addElement(pathfinder);
        }
        GraduationList.setModel(graduationModel);
    } // </editor-fold>
}
